﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Business.Log
{
    public class Logger
    {
        private static Logger instance;
        private System.IO.StreamWriter fp;
        private String path;

        private Logger()
        {
            path = AppDomain.CurrentDomain.BaseDirectory + "/Logs/";
        }

        public void Write(Exception exception)
        {
            String content = exception.Message + Environment.NewLine + exception.StackTrace + Environment.NewLine;
            if (HttpContext.Current != null)
            {
                String ip = "";// Security.SecurityContext.GetRequestIP();
                String requestPath = "";// Security.SecurityContext.GetRequestPath();
                content += String.Format("Request: {0} From {1}", requestPath, ip);
            }
            Write(content);
        }

        public void Write(string s)
        {
            try
            {
                lock (instance)
                {
                    string fileName = path  + DateTime.Now.ToString("yyyyMMddHHmm") + ".log";

                    if (System.IO.File.Exists(fileName))
                    {
                        fp = System.IO.File.AppendText(fileName);
                    }
                    else
                    {
                        fp = System.IO.File.CreateText(fileName);
                    }

                    fp.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss ") + s);
                }
            }            
            finally
            {
                if (fp != null)
                    fp.Close();
            }
        }

        public static Logger Instance
        {
            get 
            {
                if (instance == null)
                    instance = new Logger();

                return instance;
            }
        }
    }
}
